package com.ruoyi.web.controller.task;

import com.ruoyi.common.constant.VQMSConstants;
import com.ruoyi.vqms.domain.VQMSQueue;
import com.ruoyi.vqms.domain.VQMSQueueReservation;
import com.ruoyi.vqms.domain.VQMSVisitRecordYuchai;
import com.ruoyi.vqms.domain.VQMSVisitRecordYuchi;
import com.ruoyi.vqms.service.IVQMSQueueReservationService;
import com.ruoyi.vqms.service.IVQMSQueueService;
import com.ruoyi.vqms.service.IVQMSVisitRecordYuchaiService;
import com.ruoyi.vqms.service.IVQMSVisitRecordYuchiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ruoyi.common.annotation.Log;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

@Component("confirmedTask")
public class ConfirmedTask {

    @Autowired
    private IVQMSVisitRecordYuchaiService visitRecordYuchaiService;
    @Autowired
    private IVQMSVisitRecordYuchiService visitRecordYuchiService;
    @Autowired
    private IVQMSQueueReservationService queueReservationService;
    @Autowired
    private IVQMSQueueService queueService;
//    @Autowired
//    private IVQMSQueueReservationService queueReservationService;

    public void confirmedYuchai() {
        System.out.println("执行玉柴系统确认定时任务");
        //查询玉柴昨日未确认
        List<VQMSVisitRecordYuchai> yuchaiList = visitRecordYuchaiService.selectYuchaiWaitingConfirmed();
        if (!yuchaiList.isEmpty()) {
            for (VQMSVisitRecordYuchai yuchai : yuchaiList) {
                yuchai.setRegistrationStatus(2);    //已确认
                yuchai.setConfirmedBy(2);           //系统确认
                yuchai.setConfirmedTime(new Date());
                visitRecordYuchaiService.update(yuchai);
            }
        }
    }

    public void confirmedYuchi() {
        System.out.println("执行玉驰系统确认定时任务");
        //查询玉驰昨日未确认
        List<VQMSVisitRecordYuchi> yuchiList = visitRecordYuchiService.selectYuchiWaitingConfirmed();
        if (!yuchiList.isEmpty()) {
            for (VQMSVisitRecordYuchi yuchi : yuchiList) {

                if (yuchi.getReservationId() != null) {  //完成预约
                    VQMSQueueReservation reservation = queueReservationService.getById(yuchi.getReservationId());
                    if (reservation != null) {
                        reservation.setStatus(VQMSConstants.STATUS_RESERVATION_END);
                        int i = queueReservationService.update(reservation);
                    }
                }

                yuchi.setRegistrationStatus(2);    //已确认
                yuchi.setConfirmedBy(2);           //系统确认
                yuchi.setConfirmedTime(new Date());
                visitRecordYuchiService.update(yuchi);
            }
        }

    }

    public void factoryYuchai() {
        System.out.println("执行玉柴超时自动出厂定时任务");
        List<VQMSVisitRecordYuchai> yuchaiList = visitRecordYuchaiService.getFactoryTimeout();
        if (!yuchaiList.isEmpty()) {
            for (VQMSVisitRecordYuchai visitRecordYuchai : yuchaiList) {
                //赋值出厂时间
                try {
                    Date createTime = visitRecordYuchai.getCreateTime();
                    Instant instant = createTime.toInstant();
                    LocalDateTime dateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();

                    // 计算出厂时间（创建时间 + 2天）
                    LocalDateTime result = dateTime.plusDays(2);
                    Instant resultInstant = result.atZone(ZoneId.systemDefault()).toInstant();
                    visitRecordYuchai.setFactoryTime(Date.from(resultInstant));
                } catch (Exception e) {
                    System.out.println("出厂时间赋值失败");
                    e.printStackTrace();
                    visitRecordYuchai.setFactoryTime(new Date());
                }
                int i = visitRecordYuchaiService.update(visitRecordYuchai);
                if (i != 1) {
                    System.out.println("自动出厂修改失败：" + visitRecordYuchai.getId());
                }

                //同步玉驰记录
                if (visitRecordYuchai.getReservationId() != null) {
                    //查询同一个预约ID的玉驰访客记录
                    VQMSVisitRecordYuchi visitRecordYuchi = visitRecordYuchiService.getReservationId(visitRecordYuchai.getReservationId());
                    if (visitRecordYuchi != null) {
                        visitRecordYuchi.setFactoryTime(visitRecordYuchai.getFactoryTime());
                        int n = visitRecordYuchiService.update(visitRecordYuchi);
                        if (n != 1) {
                            System.out.println("自动出厂定时任务-同步玉驰出厂时间失败");
                        }
                    } else {
                        System.out.println("司机确认离场-未找到玉驰对应预约ID访客记录：" + visitRecordYuchai.getReservationId());
//                        logger.error("司机确认离场-未找到玉驰对应预约ID访客记录：" + visitRecordYuchai.getReservationId());
                    }
                }
            }
        }

    }

    public void confirmedQueue() {
        System.out.println("执行排队超24小时自动完成排队定时任务");
        //查询创建时间大于24小时的排队
        List<VQMSQueue> queueList = queueService.selectTimeoutList();
        queueList.forEach(queue -> {
            queue.setUpdateBy("task");
            queue.setEndTime(new Date());
            queue.setStatus(VQMSConstants.STATUS_QUEUE_END);
            //完成装卸货
            queueService.update(queue);
            //完成预约
            VQMSQueueReservation reservation = queueReservationService.getById(queue.getReservationId());
            if (reservation != null) {
                reservation.setStatus(VQMSConstants.STATUS_RESERVATION_END);
                reservation.setCompleteTime(new Date());
                reservation.setUpdateBy("task");
                queueReservationService.update(reservation);
            }
        });
//        queueList.forEach(queue -> {
//            queue.setUpdateBy("task");
//            queue.setUpdateTime(new Date());
//            if (queue.getStatus().equals(VQMSConstants.STATUS_QUEUE_LOADING)) {
//                queueService.next(queue); // 装卸货中的完成排队任务
//            } else {
//                queueService.queueNext(queue); // 排队中的完成排队任务
//            }
//        });

        //重新赋值排队序号（根据排队队列）
        processQueueArea((long) 1);    // 采购A仓
        processQueueArea((long) 41);   // 采购BC仓
        processQueueArea((long) 61);   // 主机仓

    }

    // 处理单个区域的排队队列
    private void processQueueArea(Long areaId) {
        List<VQMSQueue> queueList = queueService.selectAreaTimeoutList(areaId);
        for (int i = 0; i < queueList.size(); i++) {
            VQMSQueue queue = queueList.get(i);
            // 第一条设置为装卸货状态(2)，其余为排队中(1)
            queue.setStatus(i == 0 ? 2 : 1);
            queue.setQueueIndex(i + 1);
            queueService.update(queue);
        }
    }

}
